package com.api.sw.web;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shihua.util.BaseUtil;
import com.api.shihua.util.LogTool;
import com.api.sw.util.SWUtil;
import com.cloudstore.eccom.constant.WeaBoolAttr;
import com.cloudstore.eccom.pc.table.WeaTable;
import com.cloudstore.eccom.pc.table.WeaTableColumn;
import com.cloudstore.eccom.result.WeaResultMsg;
import weaver.conn.RecordSet;
import weaver.file.WeaverCrypto;
import weaver.general.PageIdConst;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.sql.CallableStatement;
import java.text.SimpleDateFormat;

import weaver.general.StaticObj;
import weaver.interfaces.datasource.DataSource;
import weaver.systeminfo.SystemEnv;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Path("/hr")
public class HrAction {
    private final static LogTool loghr = new LogTool("/log/hr/",false);
    @GET
    @Path("/getCustomRemainDay")
    @Produces({MediaType.TEXT_PLAIN})
    public String getCustomRemainDay(@Context HttpServletRequest request, @Context HttpServletResponse response){
        String str="";
        String EmpCode="";
        String FAmount="";
        String workflowuserid=Util.null2String(request.getParameter("workflowuserid"));//人员ID
        loghr.writeLog("workflowuserid-->"+workflowuserid);
        User user = HrmUserVarify.getUser(request, response);
        int userid= Util.getIntValue(user.getUID()+"",-1) ;
        if(!"".equals(workflowuserid)){
            userid=Util.getIntValue(workflowuserid,1);
        }
        JSONObject jsons=new JSONObject();
        RecordSet res2=new  RecordSet();

        RecordSet res1=new  RecordSet();
        if(userid<=0){
            return jsons.toJSONString();
        }
        res2.execute("select * from hrmresource where id='"+userid+"'");
        while(res2.next()){
            EmpCode=res2.getString("workcode");
        }
        SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
        String current=sim.format(new Date());
        DataSource ds =null;
        Connection conn = null;
        Statement stmt =null;
        ResultSet re =null;
        try{
            ds = (DataSource)StaticObj.getServiceByFullname(("datasource.HR"), DataSource.class);
            conn = ds.getConnection();
            stmt=conn.createStatement();
            CallableStatement cs =conn.prepareCall("{call p_GetCustomRemainDay(?,?)}");
            cs.setString(1,EmpCode);
            java.sql.Date data=new java.sql.Date(sim.parse(current).getTime());
            //cs.setDate(2,data);
            cs.setString(2,current);
            //cs.registerOutParameter(3, java.sql.Types.VARCHAR);
            //cs.registerOutParameter(4, java.sql.Types.VARCHAR);
            //cs.registerOutParameter(5, java.sql.Types.VARCHAR);
            // cs.setString(1, zt);
            // cs.setString(2, workcode);
            boolean flag=cs.execute();
            //FAmount=cs.getString(3);
            if(flag){
                ResultSet res= cs.getResultSet();
                if(res.next()){
                    FAmount=Util.null2o(res.getString(1)) ;
                }
            }


            loghr.writeLog("newgetCustomRemainDay--可调休-" + FAmount);
            stmt.close();
            conn.close();
            jsons.put("flag", true);
            jsons.put("mess", "");
            jsons.put("FAmount", FAmount);
        }catch(Exception e){
            loghr.writeLog("newgetCustomRemainDay==Exception="+e.getMessage());
            try{
                stmt.close();
                conn.close();
            }catch(Exception e1){
            }
            jsons.put("flag", false);
            jsons.put("mess", "数据库连接异常"+e.getMessage());
            jsons.put("FAmount", FAmount);
        }
        loghr.writeLog(jsons.toJSONString());
        return jsons.toJSONString();
    }

    @GET
    @Path("/checkXj")
    @Produces({MediaType.TEXT_PLAIN})
    public String checkXj(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        JSONObject JSONObject=new JSONObject();
        String EmpNo=Util.null2String(request.getParameter("EmpNo"));//工号
        String LeaveType=Util.null2String(request.getParameter("LeaveType"));//请假类别编号
        String BeginDate=Util.null2String(request.getParameter("BeginDate"));//开始日期。
        String EndDate=Util.null2String(request.getParameter("EndDate"));//结束日期
        String BeginTime=Util.null2String(request.getParameter("BeginTime"));//开始时间
        String EndTime=Util.null2String(request.getParameter("EndTime"));//结束时间
        String TimeRange=Util.null2String(request.getParameter("TimeRange"));//请假时间范围
        String OAID=System.currentTimeMillis()+"";//调用方系统中的唯一键值
        loghr.writeLog("EmpNo--"+EmpNo);
        loghr.writeLog("LeaveType--"+LeaveType);
        loghr.writeLog("BeginDate--"+BeginDate);
        loghr.writeLog("EndDate--"+EndDate);
        loghr.writeLog("BeginTime--"+BeginTime);
        loghr.writeLog("EndTime--"+EndTime);
        loghr.writeLog("TimeRange--"+TimeRange);
        String sql="select * from uf_dbhr ";
        RecordSet re=new RecordSet();
        RecordSet re1=new RecordSet();
        RecordSet re2=new RecordSet();
        RecordSet re3=new RecordSet();
        String url="";
        re.execute(sql);
        if(re.next()){
            url=Util.null2String(re.getString("url")).trim() ;
        }
        url=url+"/CheckLeaveBillValidateForApp";//GET 请求
        //拼接参数
        StringBuffer argus=new StringBuffer("?");
        argus=argus.append("EmpNo="+EmpNo);
        argus=argus.append("&LeaveType="+LeaveType);
        argus=argus.append("&BeginDate="+BeginDate);
        argus=argus.append("&EndDate="+EndDate);
        argus=argus.append("&BeginTime="+BeginTime);
        argus=argus.append("&EndTime="+EndTime);
        argus=argus.append("&TimeRange="+TimeRange);
        argus=argus.append("&Flag=7");
        argus=argus.append("&OAID="+OAID);
        loghr.writeLog(url+argus.toString());
        String result= null;
        try {
            result = SWUtil.unicodeToCn(SWUtil.postUrlDataResult(url+argus.toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //Logger log = Logger.getLogger(JSONObject.class);
        loghr.writeLog("===>"+result);
        boolean flag= SWUtil.getFloat(result);
        if(flag){
            if(Float.parseFloat(result)<=0){
                result="请假时数为0不可请假";
                flag=false;
            }
        }else{
            flag=false;
        }
        //out.clearBuffer();
        JSONObject.put("flag",flag);
        JSONObject.put("mess",result);
        return JSONObject.toJSONString();
    }
    @GET
    @Path("/getKqList")
    @Produces({MediaType.TEXT_PLAIN})
    public String getKqList(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        WeaResultMsg result = new WeaResultMsg(false);
        User user = HrmUserVarify.getUser(request, response);
        String pageID = "17ecc14c-9d64-4a43-81a4-7b7c6f7928571";
        String pageUid = pageID + "_" + 1;
        String pageSize = PageIdConst.getPageSize(pageID, 1);
        String sqlwhere = " 1=1 ";
        //新建一个weatable
        loghr.writeLog("开始 getKqList--->");
        try {
        WeaTable table = new WeaTable();
        table.setPageUID(pageUid);
        table.setPageID(pageID);
        table.setPagesize(pageSize);
        //初始化 查询条件

        String fromDate = Util.null2String(request.getParameter("fromDate")).trim();
        String toDate = Util.null2String(request.getParameter("toDate")).trim();
        Calendar today = Calendar.getInstance ();
        String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
        if(fromDate.equals("")||toDate.equals("")){
            fromDate = currentDate;
            toDate = currentDate;
        }

        String subCompanyId = Util.null2String(request.getParameter("subCompanyId")).trim();
        String departmentId = Util.null2String(request.getParameter("departmentId")).trim();
        String resourceId = Util.null2String(request.getParameter("resourceId")).trim();
        String Workflowrequestid = Util.null2String(request.getParameter("wrequestid")).trim();
        //获取日期以及人员
        RecordSet WorkRec=new RecordSet();
        WorkRec.execute("select a.fcrq,a.ccrq,b.tongxwgry from formtable_main_42 a,formtable_main_42_dt3  b  where a.id=b.mainid and requestid="+Workflowrequestid);
        while(WorkRec.next()){
            fromDate=Util.null2String(WorkRec.getString("ccrq")) ;
            toDate=Util.null2String(WorkRec.getString("fcrq")) ;
            String hrmdemo=Util.null2String(WorkRec.getString("tongxwgry")).trim();
            if(!"".equals(hrmdemo)){
                resourceId=resourceId+hrmdemo+",";
            }
        }
        if(resourceId.endsWith(",")){
            resourceId=resourceId.substring(0,resourceId.length());
        }

        String beginQueryDate = fromDate+" 00:00:00";
        String endQueryDate = toDate+" 23:59:59";
        String resourceSql = "select id from HrmResource where status in (0,1,2,3,5)";
        if(!"".equals(resourceId)){
            resourceSql += " and id in ("+resourceId+")";
        }else if(!"".equals(departmentId)){
            resourceSql += " and departmentid in ("+departmentId+")";
        }else if(!"".equals(subCompanyId)){
            resourceSql += " and subcompanyid1 in ("+subCompanyId+")";
        }
        RecordSet rs=new RecordSet();
        StringBuilder sql = new StringBuilder();
        if(rs.getDBType().equals("oracle")){
            sql.append("select 'hrm'||cast(id as VARCHAR(10)) uniqueid,id,userId as operater,'hrm_sign' as operate_type,signDate as operate_date,signTime as operate_time,LONGITUDE,LATITUDE,ADDR as address,'"+SystemEnv.getHtmlLabelNames("15880,20032",user.getLanguage())+"' as remark,'' as attachment,signtype,'' as cm,'' as timezone,'' as isimport from HrmScheduleSign ");
        }else{
            sql.append("select 'hrm'+cast(id as VARCHAR(10)) uniqueid,id,userId as operater,'hrm_sign' as operate_type,signDate as operate_date,signTime as operate_time,LONGITUDE,LATITUDE,ADDR as address,'"+SystemEnv.getHtmlLabelNames("15880,20032",user.getLanguage())+"' as remark,'' as attachment,signtype,'' as cm,'' as timezone,'' as isimport from HrmScheduleSign ");
        }
        sql.append("where isInCom='1' and userId in (").append(resourceSql).append(") ");
        if(rs.getDBType().equals("oracle")){
            if(!"".equals(beginQueryDate)){
                sql.append(" AND signDate||' '||signTime>='").append(beginQueryDate).append("' ");
            }
            if(!"".equals(endQueryDate)){
                sql.append(" AND signDate||' '||signTime<='").append(endQueryDate).append("' ");
            }
            sql.append(" AND LONGITUDE is not null and LATITUDE is not null ");
        }else{
            if(!"".equals(beginQueryDate)){
                sql.append(" AND signDate+' '+signTime>='").append(beginQueryDate).append("' ");
            }
            if(!"".equals(endQueryDate)){
                sql.append(" AND signDate+' '+signTime<='").append(endQueryDate).append("' ");
            }
            sql.append(" AND LONGITUDE!='' and LATITUDE!='' ");
        }
        sql.append(" UNION ");
        if(rs.getDBType().equals("oracle")){
            sql.append(" select 'sign'||cast(id as VARCHAR(10)) uniqueid,t.id,t.operater,t.operate_type,trim(t.operate_date) as operate_date,");
            sql.append(" t.operate_time,t.longitude,t.latitude,t.address,t.remark,t.attachment,'1' as signtype from mobile_sign t ");
        }else{
            sql.append(" select 'sign'+cast(id as VARCHAR(10)) uniqueid,*,'1' as signtype from mobile_sign t ");
        }
        sql.append(" WHERE t.operater in (").append(resourceSql).append(")");
        if(rs.getDBType().equals("oracle")){
            if(!"".equals(beginQueryDate)){
                sql.append(" AND  trim(t.operate_date)||' '||t.operate_time>='").append(beginQueryDate).append("'");
            }
            if(!"".equals(endQueryDate)){
                sql.append(" AND trim(t.operate_date)||' '||t.operate_time<='").append(endQueryDate).append("'");
            }
        }else{
            if(!"".equals(beginQueryDate)){
                sql.append(" AND  t.operate_date+' '+t.operate_time>='").append(beginQueryDate).append("'");
            }
            if(!"".equals(endQueryDate)){
                sql.append(" AND t.operate_date+' '+t.operate_time<='").append(endQueryDate).append("'");
            }
        }
        //sql.append(" ORDER BY operate_date desc,operate_time desc");
        String formsql=" from ("+sql.toString()+" ) a  left join hrmresource b  on a.operater=b.id left join hrmdepartment c on b.departmentid=c.id left join HrmSubCompany d on c.subcompanyid1=d.id";
        String field=" id,operate_date,operate_time,operater,operate_type,address,remark,signtype,departmentname,lastname,SubCompanyname";
            loghr.writeLog(formsql);
            loghr.writeLog(field);
        table.setBackfields(field);
        table.setSqlform(formsql);
        table.setSqlorderby("id");
        table.setSqlprimarykey("id");
        table.setSqlwhere(sqlwhere);


        table.setSqlisdistinct("false");
        table.getColumns().add(new WeaTableColumn("id").setDisplay(WeaBoolAttr.TRUE));   //设置为不显示
        table.getColumns().add(new WeaTableColumn("20%", SystemEnv.getHtmlLabelName(33563,user.getLanguage()), "operate_date","operate_date"));
        table.getColumns().add(new WeaTableColumn("20%", SystemEnv.getHtmlLabelName(20035,user.getLanguage()), "operate_time","operate_time"));
        table.getColumns().add(new WeaTableColumn("20%", SystemEnv.getHtmlLabelName(125530,user.getLanguage()), "lastname","lastname"));
        table.getColumns().add(new WeaTableColumn("20%", SystemEnv.getHtmlLabelName(141,user.getLanguage()), "departmentname","departmentname"));
        table.getColumns().add(new WeaTableColumn("20%", SystemEnv.getHtmlLabelName(124,user.getLanguage()), "SubCompanyname","SubCompanyname"));
        table.getColumns().add(new WeaTableColumn("20%", SystemEnv.getHtmlLabelName(125531,user.getLanguage()), "address","address"));
        table.getColumns().add(new WeaTableColumn("20%", SystemEnv.getHtmlLabelName(454,user.getLanguage()), "remark","remark"));
        table.getColumns().add(new WeaTableColumn("20%", SystemEnv.getHtmlLabelName(454,user.getLanguage()), "signtype","signtype"));
        loghr.writeLog("begin--set");
        result.putAll(table.makeDataResult());
        result.put("hasRight", true);
        result.success();
        loghr.writeLog("begin--success");
        apidatas = result.getResultMap();
        apidatas.put("api_status", true);
        System.out.println("apidatas"+JSONObject.toJSONString(apidatas));
        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
        //return json.toJSONString();
    }
}
